<?php
/**
 * 对账单接口demo
 * ====================================================
 * 商户可以通过该接口下载历史交易清单。
*/
ignore_user_abort();// 即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
header("Content-type:text/html;charset=utf-8");
include_once("../WxPayPubHelper/WxPayPubHelper.php");
include_once("../../Application/User/Conf/config.php");

	//对账单日期
	/*if (!isset($_POST["bill_date"])){
		$bill_date = "20140814";
	}
	else{*/
	    //$bill_date = $_POST["bill_date"];
        $bill_date = date('Ymd', time()-24*60*60);
		//使用对账单接口
		$downloadBill = new DownloadBill_pub();
		//设置对账单接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$downloadBill->setParameter("bill_date","$bill_date");//对账单日期 
		$downloadBill->setParameter("bill_type","SUCCESS");//账单类型
		//非必填参数，商户可根据实际情况选填
		//$downloadBill->setParameter("device_info","XXXX");//设备号  
		
		//对账单接口结果
		$downloadBillResult = $downloadBill->getResult();
		//echo $downloadBillResult['return_code'];
		
		if ($downloadBillResult['return_code'] == "FAIL") {
			echo "通信出错：".$downloadBillResult['return_msg'];
		}else{
			// print_r('<pre>');
			 //echo "【对账单详情】"."</br>";
             $response = $downloadBill->response;
             $arrs = explode("\r\n",$response);
             // 第一行表头，最后三行统计数据不要
             $insert = '';
             for($i= 1;$i< count($arrs) -3; $i++) {
                 $arr = explode(",",$arrs[$i]);
                 $arr = str_replace('`','',$arr);
                 if ($i > 1)
                     $insert = $insert.',';
                 $insert = $insert."('".$arr[4]."',"."'".$arr[12]."',"."'".$arr[7]."',"."'".$arr[6]."',"."'".$arr[5]."',"."'".$arr[0]."')";
             }

            if (!empty($insert)) {
                $insert = 'insert into wp_member_pay_alog(payid,total_fee,openid,out_trade_no,transaction_id,createtime) values '.$insert;

                $urlparts = parse_url(UC_DB_DSN);
                $mysqli = new mysqli($urlparts['host'],$urlparts['user'],$urlparts['pass'],substr($urlparts['path'],1));
                $mysqli->query($insert);

                // 插入缺失数据
                $insertLost = "INSERT INTO wp_member_pay_log(payid,total_fee,openid,out_trade_no,result_code,transaction_id,createtime)"
                              ." SELECT DISTINCT payid,total_fee,openid,out_trade_no,'true',transaction_id,createtime"
                              ." FROM wp_member_pay_alog a"
                              ." WHERE DATE(createtime) = DATE_SUB(CURDATE(),INTERVAL 1 DAY)"
                              ." AND NOT EXISTS("
                              ." SELECT 1 FROM 	wp_member_pay_log l WHERE l.transaction_id = a.transaction_id"
                              .")";
                $mysqli->query($insertLost);

                // 修改状态为已支付
                $update = "UPDATE wp_member_pay p SET STATUS = 1 WHERE p.id IN (SELECT payid FROM wp_member_pay_alog a WHERE DATE(createtime) = DATE_SUB(CURDATE(),INTERVAL 1 DAY) )";
                $mysqli->query($update);

                $mysqli->close();
            }
             //print_r($insert);
			 //print_r('</pre>');
		//}
	}
	
?>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>微信安全支付</title>
</head>
<body>
	</br></br>
	<div align="center">
		<form  action="./download_bill.php" method="post">
			<p>对账单查询</p>
			<p>日期(格式：20140101): <input type="text" name="bill_date" value="<?php echo $bill_date; ?>"></p>
		    <button type="submit" >提交</button>
		</form>
		</br>

		<a href="../index.php">返回首页</a>

		</br></br>
		<?php

		?>
	</div>
</body>
</html>